package com.kcl.dfss.fragments;

import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.kcl.dfss.HistoryActivity;
import com.kcl.dfss.LocationService;
import com.kcl.dfss.LocationService.CameraConnectionCallback;
import com.kcl.dfss.TestActivity.DataAdapter;
import com.kcl.dfss.MainActivity;
import com.kcl.dfss.R;
import com.kcl.dfss.ShareAppActivity;
import com.kcl.dfss.utils.AppUtils;
import com.kcl.dfss.utils.ApplicationData;
import com.kcl.dfss.utils.UsageAdapter;
import com.kcl.dfss.utils.UsageRecord;
import com.kcl.dfss.view.CarStateView;
import com.kcl.dfss.view.SpeedPanelView;

public class StaticsFragment extends Fragment {
	private String TAG = "StaticsFragment";
	private SpeedPanelView mSpeedView = null;
	private CarStateView mDrivingStatus = null;
	private ImageView mHistory = null;
	private ImageView mShare = null;
	private ImageView mbefore = null, mafter = null;
	private TextView mTitle = null;
	private ListView mRecordList = null;
	private int mSpeed = 0;// in m/s;
	private int mOdometer = 0;
	private UsageAdapter mRecordsAdapter = null;
	private boolean StartUpdate = false;
	private LocationService mLocationService = null;
	private static final int UPDATE_SPEEDVIEW = 0;
	private Date mTodayDate;
	private Date mCurrentDate;
	private boolean DEBUG = false;
	private DataAdapter mAdapter = null;
	private ArrayList<String> mDataList = null;
	private boolean isPaused = false;

	private static final String tag = "StaticsFragment";

	private CameraConnectionCallback mCallback = new CameraConnectionCallback() {

		@Override
		public void onCameraDisconnected() {
			// TODO Auto-generated method stub
			stopUpdateThread();
		}

		@Override
		public void onCameraConnected() {
			// TODO Auto-generated method stub
			if (isResumed()) {
				startUpdateThread();
			} else {
				StartUpdate = true;
			}
		}
	};
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE_SPEEDVIEW:
				updateSpeedView(mSpeed, mOdometer);

				// 更改行驶状态view
				if (mSpeed > 0) {
					updateCarStateView(R.drawable.car_yes_state,
							R.string.car_yes_state);
				} else {
					updateCarStateView(R.drawable.car_no_state,
							R.string.car_no_state);
				}

				if (DEBUG) {
					mAdapter.addItem("speed is " + mSpeed + "  odometer is "
							+ mOdometer);
				}
				break;
			}
		}
	};
	private UpdateThread mUpdateThread;

	public class UpdateThread extends Thread {
		public void run() {
			while (StartUpdate) {
				if (LocationService.getCamemraConnected()) {
					Location location = LocationService.getLatestLocation();
					if (location != null) {
						mSpeed = (int) location.getSpeed();
					}
					mOdometer = ((int) LocationService.getDistance());
					mHandler.sendEmptyMessage(UPDATE_SPEEDVIEW);

				}
				try {
					Thread.sleep(1500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ArrayList<UsageRecord> records = MainActivity.getAppData()
				.getUsageRecord(new Date(System.currentTimeMillis()));
		mRecordsAdapter = new UsageAdapter(getActivity(), records);

	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.layout_statics, container, false);
		mSpeedView = (SpeedPanelView) view.findViewById(R.id.speedpanel);
		mDrivingStatus = (CarStateView) view.findViewById(R.id.car_state);
		mDrivingStatus.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				/*
				 * mSpeed += 5000; if (mSpeed >= 220000) mSpeed = 0;
				 * mHandler.sendEmptyMessage(0);
				 */
			}
		});
		mRecordList = (ListView) view.findViewById(R.id.usagelog);
		mRecordList.setAdapter(mRecordsAdapter);

		mRecordList.setVisibility(View.VISIBLE);
//		if (DEBUG) {
//			mDataList = new ArrayList<String>();
//			mAdapter = new DataAdapter(getActivity(), R.layout.layout_listitem,
//					R.id.listitem, mDataList);
//			mRecordList.setAdapter(mAdapter);
//		}
		mHistory = (ImageView) view.findViewById(R.id.image_history);
		mHistory.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(getActivity(), HistoryActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				getActivity().startActivity(intent);
			}
		});
		mShare = (ImageView) view.findViewById(R.id.image_share);
		mShare.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(getActivity(), ShareAppActivity.class));
			}
		});

		mTodayDate = new Date(System.currentTimeMillis());
		mCurrentDate = mTodayDate;
		setUpListView(mTodayDate);

		mTitle = (TextView) view.findViewById(R.id.textView1);
		mbefore = (ImageView) view.findViewById(R.id.image_left);
		mafter = (ImageView) view.findViewById(R.id.image_right);
		mbefore.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mCurrentDate = getDateBefore(mCurrentDate);
				setUpListView(mCurrentDate);
				if (mCurrentDate.equals(mTodayDate)) {
					mTitle.setText("今日行程");
				} else {
					mTitle.setText(mCurrentDate.toString());
				}
			}
		});
		mafter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mCurrentDate = getDateAfter(mCurrentDate);
				// 修改内容：当前日期为最新的话提示为最新日期
				if (mCurrentDate.getTime() > mTodayDate.getTime()) {
					mCurrentDate = mTodayDate;
					Toast.makeText(getActivity(), "当前日期已为最新日期",
							Toast.LENGTH_SHORT).show();
				} else {
					setUpListView(mCurrentDate);

					if (mCurrentDate.equals(mTodayDate)) {
						mTitle.setText("今日行程");
					} else {
						mTitle.setText(mCurrentDate.toString());
					}
				}
			}
		});
		LocationService.addCameraCallback(mCallback);
		if (DEBUG) {
			startUpdateThread();
		}
		LogInsertData();
		return view;
	}

	public void updateSpeedView(final int speed, final int odometer) {
		Log.d(TAG, "updating SpeedView Speed is " + speed + " odometer is "
				+ odometer);

		mSpeedView.setSpeed((int) (speed * 3.6f + 0.5), odometer / 1000);
		// final int iSpeed = mSpeedView.getSpeed();
		// final int nSpeed = speed / 1000;
		// Toast.makeText(getActivity(),
		// "speed is " + nSpeed + " odometer is " + odometer,
		// Toast.LENGTH_SHORT).show();
		// final int interval = (nSpeed > iSpeed) ? 1 : -1;
		// Timer timer = new Timer();
		// TimerTask task = new TimerTask() {
		// @Override
		// public void run() {
		// final int speeds = mSpeedView.getSpeed();
		// if (speeds != nSpeed) {
		// getActivity().runOnUiThread(new Runnable() {
		// public void run() {
		// mSpeedView.setSpeed(speeds + interval,
		// odometer / 1000);
		// }
		// });
		// }
		// }
		// };

		// timer.schedule(task, 10, 150);
	}

	public void updateCarStateView(int resID, int text) {
		mDrivingStatus.setBackground(resID, text);
	}

	public void setUpListView(Date date) {
		Log.d(TAG, "setup list view: date is " + date.toString());
		ArrayList<UsageRecord> records = MainActivity.getAppData()
				.getUsageRecord(date);
		mRecordsAdapter.setRecordsList(records);
		mRecordsAdapter.notifyDataSetChanged();

		mSpeed = 0;
		mOdometer = 0;
		mHandler.sendEmptyMessage(0);

	}

	private void stopUpdateThread() {
		if (mUpdateThread != null) {
			StartUpdate = false;
			mUpdateThread = null;
		}
	}

	private void startUpdateThread() {
		// if (LocationService.getInstance() != null) {
		mUpdateThread = new UpdateThread();
		StartUpdate = true;
		mUpdateThread.start();
		// }
	}

	public void onPause() {
		super.onPause();
		if (StartUpdate) {
			stopUpdateThread();
			isPaused = true;
		}
	}

	public void onResume() {
		super.onResume();

		Log.i(tag, "执行StaticsFragment中onResume方法");

		if (isPaused || StartUpdate) {
			startUpdateThread();
			isPaused = false;
		}
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {

		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {

			Log.i(tag, "执行StaticsFragment中setUserVisibleHint方法");

			SharedPreferences preferences = getActivity().getSharedPreferences(
					"shared_login", 0);
			boolean login_state = preferences.getBoolean("login", false);
			if (!login_state) {
				AppUtils.showdialog(getActivity());
			}
		}
	}

	public void onDestroy() {
		super.onDestroy();

	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		if (hidden) {

			Log.i(tag, "执行StaticsFragment中onHiddenChanged方法");

			onPause();
		} else {
			onResume();
		}
		super.onHiddenChanged(hidden);
	}

	private Date getDateBefore(Date date) {
		long time = date.getTime() - 86400000;
		return new Date(time);
	}

	private Date getDateAfter(Date date) {
		long time = date.getTime() + 86400000;
		return new Date(time);
	}

	public class DataAdapter extends BaseAdapter {
		private ArrayList<String> mData = null;
		private Context mContext = null;
		private int mLayoutID = -1;
		private int mViewID = -1;
		private LayoutInflater mInflater = null;

		public DataAdapter(Context context, int resourceid, int textviewid,
				List<String> data) {
			mContext = context;
			mLayoutID = resourceid;
			mViewID = textviewid;
			mData = new ArrayList<String>(data);
			mInflater = (LayoutInflater) mContext
					.getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
		}

		public void addItem(String string) {
			mData.add(string);
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mData.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = mInflater.inflate(mLayoutID, null);
			TextView textview = (TextView) view.findViewById(mViewID);
			textview.setText(mData.get(position));
			return view;
		}
	}

	public void LogInsertData() {
		Time mStartTime = new Time(System.currentTimeMillis());
		Time mEndTime = new Time(System.currentTimeMillis() + 1000000);
		UsageRecord usage = new UsageRecord(
				getDateBefore(mCurrentDate).toString(),
				mStartTime.toString(),
				mEndTime.toString(),
				23900.0f,
				23900 / secondsBetweenTime(mStartTime, mEndTime) / 1000.0f / 3600);
		ApplicationData mData = MainActivity.getAppData();
		if (mData != null)
			mData.insertUsageRecord(usage);
	}

	public int secondsBetweenTime(Time startTime, Time endTime) {
		long interval = endTime.getTime() - startTime.getTime();
		return (int) (interval / 1000.0f);
	}

}
